package 数组题目.数组求和;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//和三数之和
//https://leetcode.cn/problems/3sum/
class 三数之和 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        //穷举第一个数，用完之后穷举下一个
        for (int i = 0; i < nums.length - 2; i++) {
            int one = nums[i];
            findTowSum(nums, i + 1, one, res);
            while (i < nums.length - 2 && one == nums[i + 1]) i++;
        }
        return res;
    }

    private static void findTowSum(int[] nums, int i, int one, List<List<Integer>> res) {
        int left = i, right = nums.length - 1;
        while (left < right) {
            int two = nums[left];
            int three = nums[right];
            if (one + two + three == 0) {
                List<Integer> ans = new ArrayList<>();
                ans.add(one);
                ans.add(two);
                ans.add(nums[right]);
                res.add(ans);
            }
            if (nums[left] + nums[right] + one < 0) {
                while (left < nums.length && two == nums[left]) left++;
            } else {
                while (right > left && three == nums[right]) right--;
            }
        }
    }
}
